package com.va.commons;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Class containing miscellaneous utilities.
 */
public class Util
{
    /**
     * Check the string which passed in as parameter is Empty or full of '\u0020' character
     *
     * @param s - the string to check
     * @return boolean value - true if s is empty string and false if otherwise
     */
    public static boolean isEmpty( String s)
    {
        if (s == null)
        {
            return true;
        } 
        
        return s.trim().length() == 0;
    }
    
    /**
     * Check the string which passed in as parameter is Empty or full of whitespace character, 
     * not only '\u0020' character
     *
     * @param s - the string to check
     * @return boolean value - true if s is blank string and false if otherwise
     */
    public static boolean isBlank( String s )
    {
        if (isEmpty(s))
        {
            return true;
        }
        
        int len = s.length();
        char flag;
        for (int i = 0; i < len; i++)
        {
            flag = s.charAt(i);
            if (!Character.isWhitespace(flag))
            {
                return false;
            }
        }
        return true;
    }
    
    /**
     * Check object is null or empty or full of whitespace character
     *
     * @param o - the object to check
     * @return boolean value - true if o is null and false if otherwise
     */
    public static boolean isNull( Object o )
    {
        if ( o == null )
        {
            return true;
        }
        
        if ( isBlank(o.toString()) )
        {
            return true;
        }

        return false;
    }

    /**
     * Creates an MD5 checksum for the string passed in as parameter
     * 
     * @param str - the string to process
     * @return the MD5 checksum for the string passed in as parameter
     */
    public static String createMD5Checksum( String str )
    {
        byte messageDigest[] = null;
        MessageDigest mDigest = null;
        StringBuilder hexString = new StringBuilder();
        try
        {
            mDigest = MessageDigest.getInstance( "MD5" );
            mDigest.reset();
            byte[] mybytes = str.getBytes();
            mDigest.update( mybytes );
            messageDigest = mDigest.digest();
        }
        catch ( NoSuchAlgorithmException e )
        {
            System.out.println( "Cannot find digest algorithm" );
            System.exit( 1 );
        }
        
        for ( int i = 0; i < messageDigest.length; i++ )
        {
            String hex = Integer.toHexString( 0xFF & messageDigest[i] );
            if ( hex.length() == 1 )
            {
                hexString.append( '0' );
            }
            hexString.append( hex );
        }
        
        return hexString.toString();
    }
}
